package com.acane.instagram.controller;

import com.acane.instagram.pojo.ApiResponse;
import com.acane.instagram.pojo.User;
import com.acane.instagram.service.FileStorageService;
import com.acane.instagram.service.UserService;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

// File: AvatarController.java
@RestController
@RequestMapping("/api/upload")
public class AvatarController {
    private static final Logger logger = LoggerFactory.getLogger(AvatarController.class);

    @Autowired
    private UserService userService;

    @Autowired
    FileStorageService fileStorageService;

    // 构造器注入...

    @SneakyThrows
    @PostMapping("/avatar")
    public ResponseEntity<?> uploadAvatar(
            @RequestParam("file") MultipartFile file,
            @RequestParam("userId") String userId // 接收String类型用户ID
    ) {

        // 获取文件的 MIME 类型
        String contentType = file.getContentType();
        if (contentType == null) {
            return ResponseEntity.status(400).body(
                    new ApiResponse(400, "无法确定文件类型", null)
            );
        }
        boolean isImage = contentType.startsWith("image");
        boolean isVideo = contentType.startsWith("video");

        // 判断文件是否为图片或视频
        if (!isImage && !isVideo) {
            System.out.println("======================================不支持的文件类型====================================");
            return ResponseEntity.status(400).body(
                    new ApiResponse(400, "不支持的文件类型", null)
            );
        }

            // 1. 验证用户是否存在
            User user = userService.getUserById(userId);
            logger.info("User found: {}", user);
            logger.info("User found: {}", user != null);
            if (user == null) {
                return ResponseEntity.status(404).body(
                        new ApiResponse(404, "用户不存在", null)
                );
            }
            String fileName = "";
            if (isVideo) {
                // 2. 生成文件名
                fileName = UUID.randomUUID() + "_message_video.mp4";
                logger.info("Generated file name: {}", fileName);
            } else {
                fileName = UUID.randomUUID() + "_message_image.jpg";
            }



            // 3. 保存文件到指定目录
            String filePath = fileStorageService.storeFile(file, fileName);
        logger.info("Stored file path: {}", filePath);
        if (filePath == null) {
            return ResponseEntity.status(500).body(
                    new ApiResponse(500, "文件上传失败", null)
            );
        }
            // 4. 更新数据库
            userService.updateUserAvatar(userId, fileName);

            return ResponseEntity.ok(new ApiResponse(200, "上传成功", fileName));
    }



    @SneakyThrows
    @PostMapping("/media")
    public ResponseEntity<?> uploadMedia(
            @RequestParam("file") MultipartFile file
    ) {

        // 获取文件的 MIME 类型
        String contentType = file.getContentType();
        if (contentType == null) {
            return ResponseEntity.status(400).body(
                    new ApiResponse(400, "无法确定文件类型", null)
            );
        }
        boolean isImage = contentType.startsWith("image");
        boolean isVideo = contentType.startsWith("video");

        // 判断文件是否为图片或视频
        if (!isImage && !isVideo) {
            return ResponseEntity.status(400).body(
                    new ApiResponse(400, "不支持的文件类型", null)
            );
        }

        String fileName = "";
        if (isVideo) {
            // 2. 生成文件名
            fileName = UUID.randomUUID() + "_message_video.mp4";
            logger.info("Generated file name: {}", fileName);
        } else {
            fileName = UUID.randomUUID() + "_message_image.jpg";
        }

        // 3. 保存文件到指定目录
        String filePath = fileStorageService.storeFile(file, fileName);
        logger.info("Stored file path: {}", filePath);
        if (filePath == null) {
            return ResponseEntity.status(500).body(
                    new ApiResponse(500, "文件上传失败", null)
            );
        }

        return ResponseEntity.ok(new ApiResponse(200, "上传成功", fileName));

    }
}